package baseserver

import (
	"github.com/dubbogo/gost/log/logger"

	"time"
)

type BaseServer struct {
	Name       string //名称
	Interval   int32  //执行间隔 ms
	RunTimes   uint32 //执行次数
	ticker     *time.Ticker
	DoInterval func()
	DoClose    func()
}

func (p *BaseServer) Start() {
	AddServer(p)
	if p.Interval == 0 {
		p.Interval = 10000
	}
	p.ticker = time.NewTicker(time.Millisecond * time.Duration(p.Interval))
	logger.Infof("服务程序：%v 启动", p.Name)
	go func() {
		for {
			select {
			case <-p.ticker.C:
				if p.DoInterval != nil {
					p.DoInterval()
				} else {
					logger.Infof("服务程序：%v DoInterval nil", p.Name)
				}
				//p.(IDoInterval).DoInterval()
				p.ticker.Reset(time.Millisecond * time.Duration(p.Interval))
				p.RunTimes++
			}
		}
	}()
}

func (p *BaseServer) Close() {
	p.ticker.Stop()
	if p.DoClose != nil {
		p.DoClose()
	}
	logger.Infof("服务程序：%v 关闭", p.Name)
}
